package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.NewsType;
import cn.wolfcode.trip.base.mapper.NewsTypeMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.INewsTypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 不出bug- 么么哒
 * @DESCRIPTION
 * @create 2018/11/14
 */
@Service
public class NewsTypeServiceImpl implements INewsTypeService {
    @Autowired
    private NewsTypeMapper newsTypeMapper;

    @Override
    public void saveOrUpdate(NewsType entity) {
        if (StringUtils.isEmpty (entity.getName ())) {
            throw new RuntimeException ("不能保存空值");
        }
        if (entity.getType () == null) {
            int maxType = newsTypeMapper.selectMaxType ();
            entity.setType (maxType + 1);
        }
        if (entity.getId () == null) {
            if (newsTypeMapper.selectByType (entity.getType ()) != null) {
                throw new RuntimeException ("已存在相同的type");
            }
            newsTypeMapper.insert (entity);
        } else {
            newsTypeMapper.updateByPrimaryKey (entity);
        }
    }


    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage (qo.getCurrentPage (), qo.getPageSize (), qo.getOrderBy ());
        return new PageInfo (newsTypeMapper.selectForList (qo));
    }

    @Override
    public List<NewsType> list() {
        return newsTypeMapper.selectAll ();
    }
}
